<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/25
 * Time: 16:12
 */

class Ws
{
    const HOST = '0.0.0.0';
    const PORT = 8813;

    public $ws;

    public function __construct()
    {
        $this->ws = new swoole_websocket_server( self::HOST, self::PORT);

        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 2,
            'enable_static_handler' => true,
            'document_root' => '/usr/local/nginx/html/swoole/data'
        ]);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->start();
    }

    /**
     * 监听ws连接事件
     * @param $server
     * @param $request
     */
    public function onOpen($server, $request)
    {
        var_dump($request->fd);

        if ($request->fd == 1) {
            swoole_timer_tick(2000, function ($timer_id) {
                echo "2S timerId:{$timer_id}";
            });
        }
    }

    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        echo "ser-push-message:\n";
        print_r(json_decode($frame->data, true));
        echo "\n";
        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];
        //$ws->task($data);
        swoole_timer_after(5000, function () use ($ws, $frame) {
            echo "5s after\n";
            $ws->push($frame->fd, "server_timer_after");
        });
        $ws->push($frame->fd, "server-push:" . date('Y-m-d H:i:s'));
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return string
     */
    public function onTask($serv, $taskId, $workerId, $data)
    {
        print_r($data);
        sleep(10);
        return "on task finish"; //告诉worker进程
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data)
    {
        echo "taskId:{$taskId}\n";
        echo "task-finish-success:{$data}\n";
    }

    /**
     * 监听ws关闭事件
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo "clientid:{$fd}";
    }


    /**
     * 设置进程名，为后续平滑重启进程
     * @param $server
     */
    public function onStart($server) {
        swoole_set_process_name("ws_master");
    }
}

$obj = new Ws();